from django.http import HttpResponseRedirect, HttpResponse, HttpResponseNotFound, HttpResponseNotAllowed
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from intr.blog.models import BlogPost
from django.core import serializers
from intr.models.models import *
from forms import BlogPostForm
from intr.facebook_utils import *

def all_posts(request, format):
	posts = BlogPost.objects.all().order_by('added')[:100]
	if format == 'json':
		data = serializers.serialize('json', posts, fields=('title', 'author', 'added', 'content', 'society'))
		return HttpResponse(data, mimetype='application/json')
	else:
		return None


def user_posts(request, format):
	user = request.user
	if request.GET.get('username'):
		user = User.objects.get(username=request.GET.get('username'))
	
	if not user or not user.is_authenticated():
		return HttpResponseNotFound()
	
	posts = BlogPost.objects.all().filter(society__in=[s for s in user.society_set.all()]).order_by('added')[:100]
	if format == 'json':
		data = serializers.serialize('json', posts, fields=('title', 'author', 'added', 'content', 'society'))
		return HttpResponse(data, mimetype='application/json')
	else:
		return None


def create_post(request, slug):
	society = Society.objects.get(slug=slug)
	user = request.user
	
	if not society or not user.is_authenticated():
		return HttpResponseRedirect('/societies/%s/events' % society.slug)
	
	if request.POST:
		form = BlogPostForm(request.POST, instance=None)
		if form.is_valid():
			post = BlogPost()
			post.author = user
			post.society = society
			post.title = form.cleaned_data['title']
			post.content = form.cleaned_data['content']
			post.slug = post.title.strip().lower().replace(' ','-')
			post.save()
			
			if society.fb_page_access_token and society.fb_page_id:
				post_link_to_page(str(society.fb_page_id), society.fb_page_access_token, 'http://intr.ep.io/blogs/%s/%s' % (society.slug, post.slug))
			
			return HttpResponseRedirect('/societies/%s/blog' % society.slug)
	else:
		form = BlogPostForm(instance=None)
	
	return render_to_response('blog/edit.html', {'form':form, 'society':society}, context_instance=RequestContext(request))


def post(request, slug, post_slug):
	post = BlogPost.objects.get(slug=post_slug)
	society = Society.objects.get(slug=slug)
	return render_to_response('blog/post_page.html', {'post':post, 'society':society}, context_instance=RequestContext(request))